package com.itheima.mm.service.impl;

import com.itheima.mm.constant.MessageConstant;
import com.itheima.mm.dto.UserLoginDTO;
import com.itheima.mm.exception.AccountNotFoundException;
import com.itheima.mm.exception.BaseException;
import com.itheima.mm.exception.PasswordEditFailedException;
import com.itheima.mm.mapper.UserMapper;
import com.itheima.mm.pojo.User;
import com.itheima.mm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


/**
 * @program: itheima_mm
 * @ClassName UserServiceImpl
 * @description:
 * @author: lyy
 * @create: 2023-09-21 19:57
 * @Version 1.0
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Value("${mm.md5.salt}")
    private String salt;

    /**
     * 登录
     *
     * @return
     * @param: userLoginDTO
     **/
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        User user = userMapper.getByUsername(username);

        // 账号密码比对
        if (user == null) {
            // 用户名不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // md5加密
        String psd = DigestUtils.md5DigestAsHex((password + salt).getBytes());

        if (!psd.equals(user.getPassword())) {
            // 密码错误
            throw new PasswordEditFailedException(MessageConstant.PASSWORD_ERROR);
        }

        if (user.getState() == 1) {
            throw new BaseException("用户账号已被冻结，请联系管理员");
        }

        return user;

    }

}

